/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.io.IOException;
import java.util.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.bluetooth.*;


/**
 * @author alex
 */
public class BluCOM extends MIDlet implements DiscoveryListener, CommandListener {

    private boolean midletPaused = false;   
    public static final Vector/*<RemoteDevice>*/ devicesDiscovered = new Vector();
    final Object inquiryCompletedEvent = new Object();

    //<editor-fold defaultstate="collapsed" desc=" Generated Fields ">//GEN-BEGIN:|fields|0|
    private List lstBluDev;
    private Command cmdSearchBluDev;
    private Command cmdExit;
    //</editor-fold>//GEN-END:|fields|0|

    /**
     * The BluCOM constructor.
     */
    public BluCOM() {
       
    }

    private void showMessage(String message, AlertType altype, String title) {
        Alert alert = new Alert("");
        alert.setTitle(title);
        alert.setString(message);
        alert.setType(altype);
        this.getDisplay().setCurrent(alert);
    }
    
    private void searchBluDev(){
        devicesDiscovered.removeAllElements();
        getLstBluDev().deleteAll();
        synchronized(inquiryCompletedEvent) {
            try {
                boolean started = LocalDevice.getLocalDevice().getDiscoveryAgent().startInquiry(DiscoveryAgent.GIAC, this);
                if (started) {
                    showMessage("Searching...", AlertType.INFO, "Please wait!");
                    inquiryCompletedEvent.wait();
                    showMessage("Found" + devicesDiscovered.size(), AlertType.INFO, "Press a key to continue!");
                }
            } catch (BluetoothStateException ex) {
                showMessage(ex.getMessage(), AlertType.ERROR, "Error");
            } catch(InterruptedException ex) {
                showMessage(ex.getMessage(), AlertType.ERROR, "Error");
            }
        }


    }
    //<editor-fold defaultstate="collapsed" desc=" Generated Methods ">//GEN-BEGIN:|methods|0|
    //</editor-fold>//GEN-END:|methods|0|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: initialize ">//GEN-BEGIN:|0-initialize|0|0-preInitialize
    /**
     * Initilizes the application.
     * It is called only once when the MIDlet is started. The method is called before the <code>startMIDlet</code> method.
     */
    private void initialize() {//GEN-END:|0-initialize|0|0-preInitialize
        
//GEN-LINE:|0-initialize|1|0-postInitialize
        // write post-initialize user code here
    }//GEN-BEGIN:|0-initialize|2|
    //</editor-fold>//GEN-END:|0-initialize|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: startMIDlet ">//GEN-BEGIN:|3-startMIDlet|0|3-preAction
    /**
     * Performs an action assigned to the Mobile Device - MIDlet Started point.
     */
    public void startMIDlet() {//GEN-END:|3-startMIDlet|0|3-preAction
        // write pre-action user code here
        switchDisplayable(null, getLstBluDev());//GEN-LINE:|3-startMIDlet|1|3-postAction
        // write post-action user code here
    }//GEN-BEGIN:|3-startMIDlet|2|
    //</editor-fold>//GEN-END:|3-startMIDlet|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: resumeMIDlet ">//GEN-BEGIN:|4-resumeMIDlet|0|4-preAction
    /**
     * Performs an action assigned to the Mobile Device - MIDlet Resumed point.
     */
    public void resumeMIDlet() {//GEN-END:|4-resumeMIDlet|0|4-preAction
        // write pre-action user code here
//GEN-LINE:|4-resumeMIDlet|1|4-postAction
        // write post-action user code here
    }//GEN-BEGIN:|4-resumeMIDlet|2|
    //</editor-fold>//GEN-END:|4-resumeMIDlet|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: switchDisplayable ">//GEN-BEGIN:|5-switchDisplayable|0|5-preSwitch
    /**
     * Switches a current displayable in a display. The <code>display</code> instance is taken from <code>getDisplay</code> method. This method is used by all actions in the design for switching displayable.
     * @param alert the Alert which is temporarily set to the display; if <code>null</code>, then <code>nextDisplayable</code> is set immediately
     * @param nextDisplayable the Displayable to be set
     */
    public void switchDisplayable(Alert alert, Displayable nextDisplayable) {//GEN-END:|5-switchDisplayable|0|5-preSwitch
        // write pre-switch user code here
        Display display = getDisplay();//GEN-BEGIN:|5-switchDisplayable|1|5-postSwitch
        if (alert == null) {
            display.setCurrent(nextDisplayable);
        } else {
            display.setCurrent(alert, nextDisplayable);
        }//GEN-END:|5-switchDisplayable|1|5-postSwitch
        // write post-switch user code here
    }//GEN-BEGIN:|5-switchDisplayable|2|
    //</editor-fold>//GEN-END:|5-switchDisplayable|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: commandAction for Displayables ">//GEN-BEGIN:|7-commandAction|0|7-preCommandAction
    /**
     * Called by a system to indicated that a command has been invoked on a particular displayable.
     * @param command the Command that was invoked
     * @param displayable the Displayable where the command was invoked
     */
    public void commandAction(Command command, Displayable displayable) {//GEN-END:|7-commandAction|0|7-preCommandAction
        // write pre-action user code here
        if (displayable == lstBluDev) {//GEN-BEGIN:|7-commandAction|1|19-preAction
            if (command == List.SELECT_COMMAND) {//GEN-END:|7-commandAction|1|19-preAction
                // write pre-action user code here
                lstBluDevAction();//GEN-LINE:|7-commandAction|2|19-postAction
                // write post-action user code here
            } else if (command == cmdExit) {//GEN-LINE:|7-commandAction|3|26-preAction
                // write pre-action user code here
                exitMIDlet();//GEN-LINE:|7-commandAction|4|26-postAction
                // write post-action user code here
            } else if (command == cmdSearchBluDev) {//GEN-LINE:|7-commandAction|5|23-preAction
                searchBluDev();
//GEN-LINE:|7-commandAction|6|23-postAction
                // write post-action user code here
            }//GEN-BEGIN:|7-commandAction|7|7-postCommandAction
        }//GEN-END:|7-commandAction|7|7-postCommandAction
        // write post-action user code here
    }//GEN-BEGIN:|7-commandAction|8|
    //</editor-fold>//GEN-END:|7-commandAction|8|




    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: lstBluDev ">//GEN-BEGIN:|17-getter|0|17-preInit
    /**
     * Returns an initiliazed instance of lstBluDev component.
     * @return the initialized component instance
     */
    public List getLstBluDev() {
        if (lstBluDev == null) {//GEN-END:|17-getter|0|17-preInit
            // write pre-init user code here
            lstBluDev = new List("Bluetooth devices", Choice.IMPLICIT);//GEN-BEGIN:|17-getter|1|17-postInit
            lstBluDev.addCommand(getCmdSearchBluDev());
            lstBluDev.addCommand(getCmdExit());
            lstBluDev.setCommandListener(this);
            lstBluDev.setFitPolicy(Choice.TEXT_WRAP_DEFAULT);//GEN-END:|17-getter|1|17-postInit
            // write post-init user code here
        }//GEN-BEGIN:|17-getter|2|
        return lstBluDev;
    }
    //</editor-fold>//GEN-END:|17-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: lstBluDevAction ">//GEN-BEGIN:|17-action|0|17-preAction
    /**
     * Performs an action assigned to the selected list element in the lstBluDev component.
     */
    public void lstBluDevAction() {//GEN-END:|17-action|0|17-preAction
        // enter pre-action user code here
        String __selectedString = getLstBluDev().getString(getLstBluDev().getSelectedIndex());//GEN-LINE:|17-action|1|17-postAction
        // enter post-action user code here
    }//GEN-BEGIN:|17-action|2|
    //</editor-fold>//GEN-END:|17-action|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: cmdSearchBluDev ">//GEN-BEGIN:|22-getter|0|22-preInit
    /**
     * Returns an initiliazed instance of cmdSearchBluDev component.
     * @return the initialized component instance
     */
    public Command getCmdSearchBluDev() {
        if (cmdSearchBluDev == null) {//GEN-END:|22-getter|0|22-preInit
            // write pre-init user code here
            cmdSearchBluDev = new Command("Search", Command.SCREEN, 0);//GEN-LINE:|22-getter|1|22-postInit
            // write post-init user code here
        }//GEN-BEGIN:|22-getter|2|
        return cmdSearchBluDev;
    }
    //</editor-fold>//GEN-END:|22-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: cmdExit ">//GEN-BEGIN:|25-getter|0|25-preInit
    /**
     * Returns an initiliazed instance of cmdExit component.
     * @return the initialized component instance
     */
    public Command getCmdExit() {
        if (cmdExit == null) {//GEN-END:|25-getter|0|25-preInit
            // write pre-init user code here
            cmdExit = new Command("Exit", Command.EXIT, 0);//GEN-LINE:|25-getter|1|25-postInit
            // write post-init user code here
        }//GEN-BEGIN:|25-getter|2|
        return cmdExit;
    }
    //</editor-fold>//GEN-END:|25-getter|2|

    /**
     * Returns a display instance.
     * @return the display instance.
     */
    public Display getDisplay () {
        return Display.getDisplay(this);
    }

    /**
     * Exits MIDlet.
     */
    public void exitMIDlet() {
        switchDisplayable (null, null);
        destroyApp(true);
        notifyDestroyed();
    }

    /**
     * Called when MIDlet is started.
     * Checks whether the MIDlet have been already started and initialize/starts or resumes the MIDlet.
     */
    public void startApp() {
        if (midletPaused) {
            resumeMIDlet ();
        } else {
            initialize ();
            startMIDlet ();
        }
        midletPaused = false;
    }

    /**
     * Called when MIDlet is paused.
     */
    public void pauseApp() {
        midletPaused = true;
    }

    /**
     * Called to signal the MIDlet to terminate.
     * @param unconditional if true, then the MIDlet has to be unconditionally terminated and all resources has to be released.
     */
    public void destroyApp(boolean unconditional) {
    }

    public void deviceDiscovered(RemoteDevice btDevice, DeviceClass arg1) {        
        devicesDiscovered.addElement(btDevice);
        try {
            getLstBluDev().append(btDevice.getFriendlyName(false), null);
        } catch (IOException cantGetDeviceName) {
            getLstBluDev().append(btDevice.getBluetoothAddress(),null);
        }
    }

    public void servicesDiscovered(int arg0, ServiceRecord[] arg1) {
        
    }

    public void serviceSearchCompleted(int arg0, int arg1) {
        
    }

    public void inquiryCompleted(int arg0) {       
        synchronized (inquiryCompletedEvent) {
            inquiryCompletedEvent.notifyAll();
        }
    }

}
